package log

import (
	"app/config"
	"fmt"
	"os"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
)

func NewZapLogger(cfg *config.LoggerConfig) *zap.Logger {
	var writers []zapcore.WriteSyncer
	// 假设 config.Stdout 应该从传入的 cfg 参数中获取
	if cfg.Stdout {
		writers = append(writers, zapcore.AddSync(zapcore.Lock(os.Stdout)))
	}

	if cfg.Path != "" {
		lumberjackLogger := &lumberjack.Logger{
			Filename: fmt.Sprintf("%s/%s", cfg.Path, cfg.File),
			MaxAge:   int(cfg.MaxAge.Hours() / 24),
			Compress: cfg.Compress,
		}
		writers = append(writers, zapcore.AddSync(lumberjackLogger))
	}

	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.TimeEncoderOfLayout(cfg.TimeFormat)

	core := zapcore.NewCore(
		zapcore.NewJSONEncoder(encoderConfig),
		zapcore.NewMultiWriteSyncer(writers...),
		zapLevel(cfg.Level),
	)

	return zap.New(core, zap.AddCaller())
}

func zapLevel(l string) (level zapcore.Level) {
	switch l {
	case "debug":
		level = zapcore.DebugLevel
	case "info":
		level = zapcore.InfoLevel
	case "warn":
		level = zapcore.WarnLevel
	case "error":
		level = zapcore.ErrorLevel
	case "fatal":
		level = zapcore.FatalLevel
	default:
		level = zapcore.DebugLevel
	}
	return
}
